package com.hanter.demo.raddemo

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Intent
import android.content.res.Resources.NotFoundException
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.hanter.android.radlib.util.WindowUtils
import kotlinx.android.synthetic.main.activity_splash.*

class SplashActivity : AppCompatActivity() {

    private var launchView: View? = null
    private var counter = 3

    override fun onCreate(savedInstanceState: Bundle?) {
        WindowUtils.setTranslucentStatus(this, true)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

//        ViewCompat.getWindowSystemUiVisibility()

        launchView = createLaunchView()

        val contentParent = findViewById<ViewGroup>(android.R.id.content)
        val contentView = createContentView(contentParent)
        if (launchView == null) {
            setContentView(contentView)
        } else {
            addContentView(launchView, matchParent)
            addContentView(contentView, matchParent)
            window.setBackgroundDrawable(ColorDrawable(Color.WHITE));
            transitLaunchView()
        }

        btnSkip.setOnClickListener(View.OnClickListener { v: View? ->
            window.decorView.removeCallbacks(countDownRunnable)
            val intent = Intent(this@SplashActivity, MainActivity::class.java)
            startActivity(intent)
            finish()
        })
        window.decorView.postDelayed(countDownRunnable, 1000)
    }

    private fun transitLaunchView() {
        launchView?.animate()?.alpha(0f)?.setDuration(1200)?.setListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                (launchView?.parent as ViewGroup?)?.removeView(launchView)
                launchView = null
            }
        })?.start()
    }

    override fun onDestroy() {
        window.decorView.removeCallbacks(countDownRunnable)
        super.onDestroy()
    }

    private val countDownRunnable: Runnable = object : Runnable {
        override fun run() {
            counter--
            btnSkip!!.text = counter.toString() + "s"
            if (counter <= 0) {
                val intent = Intent(this@SplashActivity, MainActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                window.decorView.postDelayed(this, 1000)
            }
        }
    }

    private fun createContentView(parent: ViewGroup): View {
        return LayoutInflater.from(this).inflate(R.layout.activity_splash, parent, false)
    }

    private fun createLaunchView(): View? {
        if (showSplashScreenUntilFirstFrame()) {
            val launchScreenDrawable = launchScreenDrawableFromActivityTheme
            if (launchScreenDrawable != null) {
                val view = View(this)
                view.layoutParams = matchParent
                view.background = launchScreenDrawable
                return view
            }
        }
        return null
    }

    private val launchScreenDrawableFromActivityTheme: Drawable?
        get() {
            val typedValue = TypedValue()
            return if (!theme.resolveAttribute(android.R.attr.windowBackground, typedValue, true)) {
                null
            } else if (typedValue.resourceId == 0) {
                null
            } else {
                try {
                    resources.getDrawable(typedValue.resourceId)
                } catch (e: NotFoundException) {
                    Log.e(
                        TAG,
                        "Referenced launch screen windowBackground resource does not exist"
                    )
                    null
                }
            }
        }

    private fun showSplashScreenUntilFirstFrame(): Boolean {
        return true

//        try {
//            ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(),
//                    PackageManager.GET_META_DATA | PackageManager.GET_ACTIVITIES);
//            Bundle metadata = activityInfo.metaData;
//            return metadata != null && metadata.getBoolean(SPLASH_SCREEN_META_DATA_KEY);
//        } catch (PackageManager.NameNotFoundException e) {
//            return false;
//        }
    }

    private fun addLaunchView() {
        if (launchView != null) {
            addContentView(launchView, matchParent)
            this.window.setBackgroundDrawable(null)

//            this.flutterView.addFirstFrameListener(new FirstFrameListener() {
//                public void onFirstFrame() {
//                    MyFlutterActivityDelegate.this.launchView.animate().alpha(0.0F).setListener(new AnimatorListenerAdapter() {
//                        public void onAnimationEnd(Animator animation) {
//                            ((ViewGroup) MyFlutterActivityDelegate.this.launchView.getParent()).removeView(MyFlutterActivityDelegate.this.launchView);
//                            MyFlutterActivityDelegate.this.launchView = null;
//                        }
//                    });
//                    MyFlutterActivityDelegate.this.flutterView.removeFirstFrameListener(this);
//                }
//            });
        }
    }

    companion object {
        private const val TAG = "SplashActivity"
        private val matchParent = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT
        )
    }
}